import { common } from "js/map"
const { mimeTypeMap } = common
export default Vue => {
  Vue.prototype.$getMimeType = function(file, mimes) {
    let m = {},
      msg = ""
    if (!mimes) {
      msg = "传入accept，同时要去mimeTypeMap内配置对应的Unit8Array码"
      console.error(msg)
      Vue.prototype.$message.error(msg)
      return
    } else {
      const t = Object.prototype.toString.call(mimes).slice(8, -1)
      if (t === "String") {
        mimes = mimes.split(",")
        mimes = mimes.map(it => it.replace(".", ""))
      }
      for (let i = 0; i < mimes.length; i++) {
        const it = mimes[i]
        console.info("it", it, mimeTypeMap[it])
        if (mimeTypeMap[it]) {
          m[[mimeTypeMap[it].type]] = mimeTypeMap[it].code
        } else {
          msg = it + "未定义mimeType的特征码"
          console.error(msg)
          Vue.prototype.$message.error(msg)
          return
        }
      }
    }
    console.info("m", m)
    return new Promise((resovle, reject) => {
      let type = file.type
      let blob = file.slice(0, 4)
      let reader = new FileReader()
      console.info("type", type)
      reader.onloadend = function(e) {
        if (e.target.readyState === FileReader.DONE) {
          const bytes = new Uint8Array(e.target.result).toString()
          let mime = m[type]
          console.info("mime", mime)
          if (mime) {
            mime = mime.toString()
            console.info("mime bytes", bytes)
            if (bytes !== mime) {
              console.info("格式无法验证")
              Vue.prototype.$message.error("仅支持" + mimes.join() + "格式")
              reject()
            } else {
              console.info("checkMimeSuccess");
              resovle()
            }
          } else {
            console.info("格式不正确")
            Vue.prototype.$message.error("仅支持" + mimes + "格式")
            reject()
          }
        }
      }
      reader.readAsArrayBuffer(blob)
    })
  }
}
